import {
  selectPartsList,
  partsDetails,
  deleteParts,
  selectPartsSuppliersList,
  partsOperate,
} from '@/services/partsLib';
import Prompt from '@/components/Prompt';

export default {
  namespace: 'PartsLib',

  state: {
    selectPartsList: [],
    partsSuppliersList: {},
    partsDetails: {},
    ruleMenuConDetails: {},
    dataSourceList: [],
  },

  effects: {
    //菜单表
    *selectPartsList({ payload, callback }, { call, put }) {
      const response = yield call(selectPartsList, payload);
      const { code, data } = response;
      if (code === 0) {
        yield put({
          type: 'saveAllValus',
          payload: {
            selectPartsList: data,
          },
        });
        callback && callback(data);
      }
    },

    //新增编辑
    *partsOperate({ payload, callback }, { call }) {
      const response = yield call(partsOperate, payload);
      const message = payload.id ? `编辑${response.message}` : `新增${response.message}`;
      if (response.code === 0) {
        Prompt({ content: message });
        if (callback) callback(response.data);
      }
    },

    //详情
    *partsDetails({ payload, callback }, { call, put }) {
      const response = yield call(partsDetails, payload);
      if (response.code === 0) {
        yield put({
          type: 'saveAllValus',
          payload: {
            partsDetails: { [payload.id]: response.data },
          },
        });
        callback && callback(response.data);
      }
    },

    //删除
    *deleteParts({ payload, callback }, { call }) {
      const response = yield call(deleteParts, payload);
      const { code, message } = response;
      if (code === 0) {
        Prompt({ content: `删除${message}` });
        if (callback) callback(response.data);
      }
    },

    //供应商列表:
    *selectPartsSuppliersList({ payload, callback }, { call, put }) {
      const response = yield call(selectPartsSuppliersList, payload);
      const { code, data } = response;
      if (code !== 0) return;
      const { list, pageSize, total, pageNum } = data;
      const infoList = {
        pagination: {
          current: pageNum,
          pageSize,
          total,
        },
        list,
      };
      yield put({
        type: 'saveAllValus',
        payload: { partsSuppliersList: infoList },
      });
      callback && callback(list);
    },
  },

  reducers: {
    saveAllValus(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
